package org.example.sword2offer.primary;

/**
 * @author: lynn
 * @Descript: 树的子结构, 一般碰到树的问题，都是用递归
 * ps：输入两棵二叉树A，B，判断B是不是A的子结构。我们约定空树不是任意一个树的子结构
 * @date: 2021/3/10 0:33
 * @version: 1.0
 */
public class Q17_HasSubtree {
    public static void main(String[] args) {
        TreeNode pTreeNode=new TreeNode(10);
        pTreeNode.left=new TreeNode(7);
        pTreeNode.right=new TreeNode(12);
        pTreeNode.left.left=new TreeNode(3);
        pTreeNode.left.right=new TreeNode(4);
        pTreeNode.right.left=new TreeNode(11);
        pTreeNode.right.right=new TreeNode(13);

        TreeNode subTreeNode=new TreeNode(7);
        subTreeNode.left=new TreeNode(3);
        subTreeNode.right=new TreeNode(4);
        System.out.println(Boolean.toString(HasSubtree(pTreeNode,subTreeNode)));
    }

    public static boolean HasSubtree(TreeNode root1,TreeNode root2) {
        if(root1 == null || root2 == null){
            return false;
        }

        return process(root1, root2);
    }

    public static boolean process(TreeNode root1, TreeNode root2){
        //审题: 题目要求输入两棵二叉树A，B，判断B是不是A的子结构 root2是B，B为空了，就说明已经遍历完了
        if(root2 == null){
            return true;
        }
        if(root1 == null && root2 != null){
            return false;
        }

        if(root1.val == root2.val){
            if(process(root1.left, root2.left) && process(root1.right, root2.right)){
                return true;
            }
        }

        return process(root1.left, root2) || process(root1.right, root2);
    }




    private static class TreeNode{
        int val=0;
        TreeNode left=null;
        TreeNode right=null;

        public TreeNode(int val) {
            this.val = val;
        }
    }
}
